# pk/LoginUi.py
from datetime import datetime
from tkinter import ttk

import mysql.connector

from pk.SetupUi import SetupUi


class LoginUi:
    def __init__(self, root):
        self.root = root
        self.root.title("登录界面")
        self.root.geometry("650x400")

        # 密钥输入框
        self.key_label = ttk.Label(root, text="请输入密钥:")
        self.key_label.pack(pady=20)
        self.key_entry = ttk.Entry(root, show="*")
        self.key_entry.pack(pady=10)

        # 登录按钮
        self.login_button = ttk.Button(root, text="登录", command=self.check_key)
        self.login_button.pack(pady=20)

        # 错误信息标签
        self.error_label = ttk.Label(root, text="", foreground="red")
        self.error_label.pack(pady=10)

    def check_key(self):
        key = self.key_entry.get()
        try:
            # 连接到 MySQL 数据库
            connection = mysql.connector.connect(
                host="120.46.184.82",
                port=9386,
                user="v3",
                password="Ryh@362524",
                database="v3"
            )
            cursor = connection.cursor()

            # 查询数据库中是否有该密钥记录，并检查是否在有效时间内
            query = "SELECT * FROM keys_table WHERE key_value = %s AND valid_until >= %s"
            now = datetime.now()
            cursor.execute(query, (key, now))
            result = cursor.fetchone()

            if result:
                try:
                    app = SetupUi()  # 打开功能界面
                    self.root.destroy()  # 关闭登录界面
                    app.root.mainloop()
                except ImportError as e:
                    print(f"模块导入错误: {e}")
                    self.error_label.config(f"模块导入错误: {e}")
                    self.error_label.config("错误, 无法加载功能界面，请稍后重试！")
            else:
                self.error_label.config(text="密钥错误或已过期，请重新输入！")

        except mysql.connector.Error as err:
            error_message = f"数据库错误: {err}"
            print(error_message)
            self.error_label.config(text=error_message)
        finally:
            if 'connection' in locals() and connection.is_connected():
                cursor.close()
                connection.close()
